package com.njwb.reflect;

import java.lang.reflect.Field;

/**
 * Description: 类的描述
 * Author: yuandeyin@itany.com
 * Date: 2025-08-07 13:53
 * Version: 1.0
 */
public class TestField {
    public static void main(String[] args) {
        try {
            Class personClass = Class.forName("com.njwb.reflect.Person");
            //获取类的属性
            //获取所有的属性
//            Field [] fields = personClass.getDeclaredFields();
//            System.out.println(fields.length);
//            for(Field f : fields){
//                System.out.println(f.getName());
//            }
//            Field [] fields = personClass.getFields();
//            System.out.println(fields.length);

            //获取指定的属性
            Field nameField = personClass.getDeclaredField("name");
            //访问修饰符  0:默认  2：private  4:protected  1:public
            System.out.println(nameField.getModifiers());
            //属性的类型
            System.out.println(nameField.getType().getSimpleName());
            //属性的名称
            System.out.println(nameField.getName());

            //拿属性的目的是赋值
            //传统的对象
//            Person person = new Person();
//            person.setName("张三");
//            System.out.println(person);

            //反射的方式赋值
            Person person = new Person();
            //对于私有属性，反射修改访问权限
            nameField.setAccessible(true);
            nameField.set(person,"我被赋值了");
            System.out.println(person);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
